package com.ruoyi.master.config.redis;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.master.service.ITTaskService;
import com.ruoyi.system.api.RemoteWeixinService;
import com.ruoyi.system.api.domain.WxText;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class WechatStreamListener implements StreamListener<String, ObjectRecord<String, String>> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisStreamConfig redisStreamConfig;

    @Autowired
    ITTaskService taskService;

    @Autowired
    RemoteWeixinService remoteWeixinService;


    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    @Override
    public void onMessage(ObjectRecord<String, String> message) {
        try{
            // 消息ID
            RecordId messageId = message.getId();

            // 消息的key和value
            String string = message.getValue();
            logger.info("wxchat-stream获取到数据。messageId={}, stream={}, body={}", messageId, message.getStream(), string);
            WxText data = JSONObject.parseObject(string, WxText.class);
            //业务逻辑
            logger.info("开始处理业务逻辑++++++++++++++");
            String replyText = taskService.insertTaskFromWechat(data);
            logger.info("replyText:{},fromOpenId:{}",replyText,data.getFromOpenId());
            remoteWeixinService.wxMpKefuMessage(data.getFromOpenId(), replyText, SecurityConstants.INNER);
            // 通过RedisTemplate手动确认消息
            this.stringRedisTemplate.opsForStream().acknowledge(redisStreamConfig.getWechatgroup(), message);
        }catch (Exception e){
            // 处理异常
            e.printStackTrace();
        }
    }
}

